package ru.compscicenter.databases.zaikina.common.model;

import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class Node implements JSONAware {
    private int nodeId;
    private int type;
    private String address = "127.0.0.1";
    private int port;


    private Node() { }

    public int getNodeId() {
        return nodeId;
    }

    public int getType() {
        return type;
    }

    public String getAddress() {
        return address;
    }

    public int getPort() {
        return port;
    }

    public String toJSONString() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", nodeId);
        jsonObject.put("type", type);
        jsonObject.put("address", address);
        jsonObject.put("port", port);
        return jsonObject.toString();
    }

    public static Node parse(String jsonStr) {
        Node node = new Node();
        try {
            JSONObject obj = (JSONObject) JSONValue.parse(jsonStr);
            node.nodeId = Integer.parseInt(obj.get("id").toString());
            node.type = Integer.parseInt(obj.get("type").toString());
            node.port = Integer.parseInt(obj.get("port").toString());
            node.address = obj.get("address").toString();
        } catch (Exception ex) {
            return null;
        }
        return node;
    }

    ///Used in package utils (ConstructConfigFile)
    public static Node constructNode(int id, int type, int port, String address) {
        Node node = new Node();
        node.nodeId = id;
        node.address = address;
        node.type = type;
        node.port = port;
        return node;
    }

    ///Used in package utils (ConstructConfigFile)
    public static Node constructNode(int id, int type, int port) {
        return constructNode(id, type, port, "127.0.0.1");
    }
}
